<!--
 * @Description: Description
 * @Author: zhaojiansen
 * @Date: 2022-10-31 16:41:29
 * @LastEditors: zhaojiansen
 * @LastEditTime: 2022-12-01 15:16:28
-->
<template>
  <div class="ceateEditor">
    <div class="ceateEditorHeight" style="display: flex">
      <div class="text">{{ pageTitle }}</div>
      <div class="button">
        <el-button type="primary" @click="submitButton('form')" :loading="sureLoading">确定</el-button>
        <el-button @click="cancelCreate">取消</el-button>
      </div>
    </div>
    <div class="ceateEditorContent">
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="欢迎语名称" prop="welcomeName">
          <el-input v-model="form.welcomeName" placeholder="请输入欢迎语名称" style="width: 350px;"></el-input>
        </el-form-item>
        <el-form-item label="执行员工" prop="userIds">
          <el-button class="button-new-tag" size="small" @click="handleClick">
            <svg-icon icon-class="add" />
            添加员工
          </el-button>
          <div v-if="scrmPersonSopUserRels.length > 0">
            <el-tag v-for="item in scrmPersonSopUserRels" :key="item.userId" closable @close="handleCloseCus(item)">
              {{ item.userName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="生效时间" prop="date1">
          <el-col :span="11">
            <el-time-picker is-range v-model="form.date1" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="HH:mm:ss" @change="dataclick(form.date1)">
            </el-time-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="文本内容" prop="welcomeMsg">
          <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" maxlength="400" show-word-limit v-model="form.welcomeMsg" placeholder="请输入文本内容" style="width: 90%;"></el-input>
        </el-form-item>
        <el-form-item label="选择素材">
          <NormalSelectMaterial v-if="operateFlag" :selectedList="form.mediaContentDetails" @confirmSelect="confirmSelectFn" />
        </el-form-item>
        <el-form-item label="二维码">
          <NormalQrCode v-if="operateFlag" :codeInfo="codeParams" @selectedSure="qrCodeConfrim" @deleteSeletedQrcode="deleteSeletedQrcode" />
        </el-form-item>
      </el-form>
    </div>
    <SelectUser :selectList="tableDataName" :visible.sync="selectUserVisible" :userList="[]" @confirm="selectUserConfirm" :is-active="'1'"></SelectUser>
  </div>
</template>

<script>
import { compile, createEditor } from '@/api/createGreeting/createEditor.js'
import { detailsInterface } from '@/api/createGreeting/messagedetails.js'
import { getCustCode, groupCode, verbalList } from '@/api/operate/verbalTrick'
import SelectUser from "@/components/SelectUser/index.vue";

export default {
  components: { SelectUser },
  data() {
    return {
      pageTitle: '创建欢迎语',
      operateFlag: '',
      dialogFormVisible: false,
      judgementCondition: '',
      form: {
        welcomeName: '',
        userNames: '',
        userIds: '',
        date1: '',
        welcomeMsg: '',
        startValidTime: '',
        endValidTime: '',
        id: this.$route.query.id,
        material: '',
        mediaId: '',
        codeUrl: '',
        qrType: '',
        activityName: '',
        welcomeMsgTplType: 2,
        mediaContentDetails: [],
        codeState: '1'
      },
      staffName: '',
      codeType: 1, //1表示员工 2：渠道 3：群活码
      codeVisible: false,
      cheackId: false,
      value1: [],
      fileList: [],
      list: [],
      loading: false,
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 20
      },
      tableData: [],
      rules: {
        welcomeName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        date1: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }
        ],
        welcomeMsg: [
          { required: true, message: '请填写活动形式', trigger: 'blur' },
          {
            min: 5,
            max: 400,
            message: '长度在 5 到 400 个字符',
            trigger: 'blur'
          }
        ]
      },
      currentRow: {},
      scrmPersonSopUserRels: [],
      tableDataName: [],
      selectUserVisible: false,
      sureLoading: false, //确定按钮
      codeParams: {
        qrState: '1',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: ''
      },
    }
  },
  watch: {
    list: {
      deep: true,
      handler(ter) {
        this.form.material = ter
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 删除二维码
    deleteSeletedQrcode() {
      this.codeParams.qrType = '';
      this.codeParams.activityName = '';
      this.codeParams.codeUrl = '';
      this.codeParams.qrId = '';
    },
    qrCodeConfrim(data) {
      if (data) {
        this.codeParams = {
          qrState: data.qrState,
          qrType: data.qrType,
          activityName: data.activityName,
          codeUrl: data.qrCode || data.codeUrl,
          qrId: data.qrId
        }
      } else {
        this.codeParams = {
          qrState: 1,
          qrType: '',
          activityName: '',
          codeUrl: '',
          qrId: ''
        }
      }
    },
    // 清除全选
    selectAll() {
      this.$refs.multipleTable.clearSelection() //清除选择
    },
    // 实现单选
    handleSelectionChange(val, row) {
      this.$refs.multipleTable.clearSelection() //清除选择
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.chat_id_list = row.groupId
      this.currentRow = row
    },
    handleSizeChange(value) {
      this.page.pageNum = 1
      this.page.pageSize = value
    },
    handleCurrentChange(value) {
      this.page.pageNum = value
    },
    selectCode(type) {
      this.codeType = type
      // this.loading = true;
      if (this.codeType === 3) {
        this.groupCode(type)
      } else if (this.codeType === 2) {
        this.verbalList(type)
      } else if (this.codeType === 1) {
        this.getCustCode()
      } else {
        this.codeVisible = true
      }
    },
    groupCode() {
      groupCode({ pageNum: 1, pageSize: 20, activityName: '' }).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows
        res.rows.forEach(item => {
          item.groupWays = item.groupWays == 0 ? '群二维码拉群' : '企微活码拉群'
        })
      })
    },
    verbalList(type) {
      verbalList({ levelType: type, mediaType: 1, tabsType: 0 }).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows
      }).catch((err) => {})
    },
    getCustCode() {
      getCustCode({ pageNum: 1, pageSize: 20, name: '' }).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows
      }).catch((err) => {})
    },
    dataclick(data) {
      data = data.join('')
      this.form.startValidTime = data.slice(0, 8)
      this.form.endValidTime = data.slice(8, 16)
    },
    getList() {
      if (this.$route.query.id) {
        this.pageTitle = "编辑欢迎语";
        this.loading = true
        const data = {
          id: this.$route.query.id,
          mediaId: this.$route.query.mediaId
        }
        detailsInterface(data).then((res) => {
          this.form = res.data
          this.codeParams = {
            qrState: this.form.codeState,
            qrType: res.data.qrType || '',
            activityName: res.data.activityName || '',
            codeUrl: res.data.codeUrl || ''
          }

          let cusIdArr, cusNameArr;
          cusIdArr = res.data.userIds.split(',')
          cusNameArr = res.data.userNames.split(',')

          //定义一个新数组，将两个数组合并到一个里面
          const zip = ([x, ...xs], [y, ...ys]) => {
            if (x === undefined || y === undefined) {
              return []
            } else {
              return [[x, y], ...zip(xs, ys)]
            }
          }
          let result = zip(cusIdArr, cusNameArr).map(([userId, userName]) => ({ userId, userName }))
          this.scrmPersonSopUserRels = result || []
          this.$set(this.form, 'date1', this.form.startValidTime + '-' + this.form.endValidTime)
          this.form.date1 = this.form.date1.split('-')
          this.operateFlag = this.$route.query.operateFlag;
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.operateFlag = this.$route.query.operateFlag;
      }
    },
    compile() {
      let userIdArr = this.scrmPersonSopUserRels.map(item => item.userId) || [];
      this.form.userIds = userIdArr.join(',')
      this.form.userNames = userIdArr.join(',')
      if (+this.form.codeState == 0) {
        this.form.qrType = this.codeParams.qrType || ''
        this.form.activityName = this.codeParams.activityName || ''
        this.form.codeUrl = this.codeParams.codeUrl || ''
      }
      compile(this.form).then((res) => {
        if (res.code === 200) {
          this.$router.push({ path: 'createGreeting' })
          this.$message.success('编辑成功!')
          this.sureLoading = false
        }
      }).catch(() => {
        this.sureLoading = false
      })
    },
    cancelCreate() {
      this.$router.push({ path: 'createGreeting' })
    },
    submitButton(form) {
      this.form.mediaContentDetails.forEach(item => {
        if (item.mediaType == '3') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkFile?id=' + item.id
        } else if (item.mediaType == '4') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkArticle?id=' + item.id
        } else if (item.mediaType == '10') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkForm?id=' + item.id
        }
      })

      if (this.scrmPersonSopUserRels && this.scrmPersonSopUserRels.length > 0) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if (this.form.mediaContentDetails.length > 9) {
              this.$message.error("所有素材不能超过九个！")
              return
            }
            if (this.codeParams.qrState == '0' && !this.codeParams.codeUrl) {
              this.$message.error('请选择二维码！');
              return
            }
            this.sureLoading = true;
            if (this.$route.query.id) {
              this.compile()
            } else if (!this.$route.query.id) {
              this.createEditor()
            }
          } else {
            this.$message.error('您还未录入完成，请核对后提交！')
            this.sureLoading = false
            return false
          }
        })
      } else {
        this.$message.error('请添加至少一位员工！')
        this.sureLoading = false
      }

    },
    createEditor() {
      let userIdArr = this.scrmPersonSopUserRels.map(item => item.userId) || []
      this.form.userIds = userIdArr.join(',')
      this.form.userNames = userIdArr.join(',')
      if (+this.form.codeState == 0) {
        this.form.qrType = this.codeParams.qrType || ''
        this.form.activityName = this.codeParams.activityName || ''
        this.form.codeUrl = this.codeParams.codeUrl || ''
      }
      createEditor(this.form).then((res) => {
        if (res.code === 200) {
          this.$router.push({
            path: 'createGreeting'
          })
          this.$message({
            type: 'success',
            message: '创建成功!'
          })
          this.sureLoading = false
        }
      }).catch(() => {
        this.sureLoading = false
      })
    },

    //添加员工
    handleClick() {
      // let arr = []
      // if (this.scrmPersonSopUserRels) this.scrmPersonSopUserRels.forEach(item => arr.push(item.userName))
      this.tableDataName = this.scrmPersonSopUserRels || []
      this.selectUserVisible = true
    },
    //删除员工
    handleCloseCus(item) {
      console.log(item, 'item', '@@@@@@')
      this.scrmPersonSopUserRels = this.scrmPersonSopUserRels.filter((x) => {
        return x.userId != item.userId
      })
    },
    //选中的员工数据
    selectUserConfirm(value) {
      // if(value && value.length > 1){
      //   this.$message.error('只支持选中一个员工');
      //   this.selectUserVisible = true;
      // }else{
      this.scrmPersonSopUserRels = []
      value.forEach((item) => {
        this.scrmPersonSopUserRels.push({
          ...item
        })
      })
      // }
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.form.mediaContentDetails = val;
    },
  },
}
</script>

<style lang="scss" scoped>
.ceateEditor {
  .ceateEditorHeight {
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    background-color: white;
    height: 70px;
    padding-left: 20px;
    padding-right: 20px;
    border-radius: 6px;

    .text {
      font-size: 20px;
    }
  }

  .ceateEditorContent {
    background-color: white;
    border-radius: 6px;
    padding: 10px 0;
  }
}

.block-wrap {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  font-weight: 600;
  color: #2a2a2a;
  font-size: 12px;
  font-family: PingFangSC-Medium, PingFang SC;

  .block-item {
    width: 80px;
    padding: 5px 0;
    margin: 10px;
    //   border: $normalBorder;
    text-align: center;

    .svg-icon {
      width: 4em;
      height: 3em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
    }
  }
}

.cutTap {
  display: flex;
  // justify-content: space-between;

  div {
    width: 100px;
  }

  .left {
    width: 100px;

    height: 40px;
    line-height: 40px;
    font-size: 15px;
    font-weight: 900;
    color: #787878;
    border-radius: 5px;
    text-align: center;
    border: 1px solid #dbd5d5;
  }

  .right {
    width: 100px;

    height: 40px;
    line-height: 40px;
    font-size: 15px;
    font-weight: 900;
    border: 1px solid #dbd5d5;
    color: #787878;
    background-color: #f5f5f5;
    border-radius: 5px;
    text-align: center;
  }
}

// 点击tap之后的效果
.active {
  width: 42%;
  background-color: #fafafa;
  height: 40px;
  line-height: 40px;
  font-size: 15px;
  font-weight: 900;
  border: 1px solid red;
  border-radius: 5px;
  text-align: center;
  color: #082aff;
}

.upload-list {
  border-radius: 5px;
  width: 500px;
  background-color: #fce0d9;
  margin-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
}

.block-wrap {
  margin-left: -10px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  font-weight: 400;
  color: #2a2a2a;
  font-size: 12px;
  font-family: PingFangSC-Medium, PingFang SC;

  .block-item {
    width: 80px;
    padding: 5px 0;
    margin: 10px;
    // border: $normalBorder;
    text-align: center;

    .svg-icon {
      width: 4em;
      height: 3em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
      margin-top: 12px;
    }

    div {
      margin-top: -10px;
    }
  }
}
</style>
